package cn.wellwan.mybatis;

import cn.wellwan.mybatis.dao.UserDao;
import cn.wellwan.mybatis.entity.User;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.*;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * Hello world!
 */
public class App {
    public static void main (String[] args) throws IOException {
//        defaultGetSqlSession();
        queryMapper();
    }


    /**
     * 配置文件生成方式 比较灵活，修改配置不用修改代码
     */
    public static SqlSessionFactory defaultGetSqlSession() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //SqlSessionFactoryBuilder 生命周期在构建了SqlSessionFactory 就被生命周期就完成了
        //SqlSessionFactory是单列的 生命周期 在mybatis 的使用过程中
        //SqlSession 生命周期 在数据库处理事务的过程中
        //Mapper 是方法级别的东西，最大作用范围就是SqlSession的生命周期
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      return sqlSessionFactory;
    }

    /**
     * 使用代码生成方式，修改配置要修改代码
     * @throws IOException
     */
    public static SqlSessionFactory getDateSource() throws IOException {
        //创建数据源
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://123.206.200.173:3306/wellwan");
        dataSource.setUsername("root");
        dataSource.setPassword("wellwan123_CN");
        //创建事务管理
        TransactionFactory  transactionFactory = new JdbcTransactionFactory();
        //数据库运行环境
        Environment environment = new Environment("development" , transactionFactory , dataSource);
        //创建配置对象
        Configuration configuration = new Configuration(environment);
        //注册一个mybatis上下文别名
        configuration.getTypeAliasRegistry().registerAlias("user" , User.class);
        //加入一个映射器
        configuration.addMapper(UserDao.class);
//        configuration.addMappers("cn.wellwan.mybatis/mapper/UserMapper.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory;

    }

    public static void queryMapper() throws IOException {
//        SqlSessionFactory sqlSessionFactory = getDateSource();
        SqlSessionFactory sqlSessionFactory = defaultGetSqlSession();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> users = mapper.selectUserList();
    }
}
